package com.wangpu.oa.dao;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;




public class SqlSessionUtil {
	private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();
	private static final SqlSessionFactory SQL_SESSION_FACTORY = create();
	
	private static SqlSessionFactory create() {
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
		InputStream in = SqlSessionUtil.class.getResourceAsStream("/mybatis.xml");
		return ssfb.build(in);
	}

	public static SqlSession getSession() {
		SqlSession session = THREAD_LOCAL.get();
		if (session == null) {
			session = SQL_SESSION_FACTORY.openSession();
			THREAD_LOCAL.set(session);
		}
		return session;
	}

	public static void closeConnection() {
		SqlSession session = THREAD_LOCAL.get();
		if (session != null) {
			THREAD_LOCAL.remove();
			session.close();
		}
	}
}
